package com.test.web.controller;
/**
 * 
 * @author 董赟赟
 *
 */
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ImageServlet
 */
@WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BufferedImage bi=new BufferedImage(70, 25, BufferedImage.TYPE_INT_RGB);//创建图像缓冲
		Graphics g=bi.getGraphics();  //创建Graphics对象,其作用相当于画笔 
		 Color c=new Color(200,150,255); //创建颜色
		 /*根据背景画了个矩形框
		  */
		 g.setColor(c);//为画布创建背景颜色
		 g.fillRect(0, 0, 70, 25);//fillRect:填充指定的矩形
		 char[] ch="ABCDEFGHIJKMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz123456789".toCharArray();//转化为字符型的数�?
		 Random r=new Random();
		 int len=ch.length;
		 int index; //index用于存放随机数字
		 StringBuffer sb=new StringBuffer();
		 for(int i=0;i<4;i++) {
			 index=r.nextInt(len);//产生随机数字
			 g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));  //设置颜色
			 g.drawString(ch[index]+"",(i*15)+3, 18);//画数字以及数字的位置
			 sb.append(ch[index]);
		 }
		 for (int i = 0; i < 2; i++) {//画两条随机的干扰线
				g.setColor(new Color(r.nextInt(200), r.nextInt(200), r
						.nextInt(200)));
				int x1 = r.nextInt(68);
				int x2 = r.nextInt(68);
				int y1 = r.nextInt(22);
				int y2 = r.nextInt(22);
				g.drawLine(x1, y1, x2, y2);
			}
		 request.getSession().setAttribute("piccode",sb.toString()); //将数字保留在session中，
		 ImageIO.write(bi, "JPG", response.getOutputStream()); 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
